<?php

namespace App\Front;

use App\Http\Controllers\Controller;
use App\Models\Wxuser;
use Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Validation\Rule;
use Log;

/**
 * 帐号登录注册管理
 * @package App\Api\User
 */
class WechatController extends Controller
{

    protected $api = "https://api.weixin.qq.com";

    public function authWechat(Request $request)
    {
        $app_id = env("APP_ID");
        $appsecret = env("APP_SECRET");
        $response = Http::get($this->api."/sns/jscode2session?appid=".$app_id."&secret=".$appsecret.
            "&js_code={$request->code}&grant_type=authorization_code")
            ->throw()->json();

        return $response;
    }

    public function login(Request $request)
    {
        $openid = $request['openid'];
        if ($openid) {

//            用户登录成功
            //从用户表中查询用户是否存在
            $wxuser = Wxuser::where('openid', $openid)->first();

            if ($wxuser) {
//当前微信用户wxuser santum登录
                Auth::login($wxuser);
                return $this->message('欢迎再次登录', [
                    'token' => $wxuser->createToken('wxuser')->plainTextToken,
                    'wxuser' => Auth::user(),
                    'is_admin' => Auth::user()->villages()->count() > 0 ? true : false
                ]);

            } else {
                //用户不存在，新增用户

                $data = [
                    'nickName' => $request->nickName,
                    'openid' => $openid,
                    'avatarUrl' => $request->avatarUrl,
                    'city' => $request->city,
                    'country' => $request->country,
                    'gender' => $request->gender,
                    'language' => $request->language,
                    'province' => $request->province
                ];
//                创建新用户
                $wxuser = Wxuser::create($data);
                Auth::login($wxuser);

//                返回token
                return $this->message('欢迎注册',
                    [
                        'token' => $wxuser->createToken('wxuser')->plainTextToken,
                        'wxuser' => Auth::user(),
                        'is_admin' => Auth::user()->villages()->count() > 0 ? true : false
                    ]);

            }
        } else {
//            用户登录失败
            return response()->json(['code' => 0, 'msg' => 'open_id未获取']);
        }
    }

    public function logout()
    {
        Auth::user()->tokens()->delete();
        return $this->message('帐号退出成功');
    }

    //通过微信获取用户手机号
    public function getPhoneNumber(Request $request)
    {
        $code = $request->code;
        $res = $this->getAccess();
        $access_token = $res->access_token;
        $headers = [
            'Content-Type' => 'application/json',
            "Accept" => "application/json"
        ];
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=".$access_token;
        $client = new \GuzzleHttp\Client();
        $response = $client->post($url, [
            'headers' => $headers,
            'body' => json_encode([
                    "code" => $code
                ]
            )
        ]);
        $result = $response->getBody()->getContents();
        $result = json_decode($result, true);
        $phoneNumber = $result['phone_info']['phoneNumber'];
        $wxuser = Wxuser::find($request->wxuser_id);
        $wxuser->mobile = $phoneNumber;
        $wxuser->save();
        return $this->message("绑定成功");
    }

    protected function getAccess()
    {
        //小程序appid appsecret
        $appid = env('APP_ID');
        $appsecret = env("APP_SECRET");
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
        $client = new \GuzzleHttp\Client();
        $response = $client->get($url);
        $result = $response->getBody()->getContents();
        return json_decode($result);
    }

    public function updateInfo(Request $request)
    {
        $wxuser = Auth::user();
        $request->validate([
            "mobile" => ['required', Rule::unique("wxusers", "mobile")->ignore($wxuser)]
        ]);

        $wxuser->update($request->input());
        return $this->message("修改成功", ['wxuser' => Auth::user()]);
    }

}
